import { Component, ViewEncapsulation, OnInit } from '@angular/core';
import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';
import { UserService } from '../user/user.service';
import { User } from '../user/user';

import { Router } from '@angular/router';

@Component({
  selector: 'login',
  encapsulation: ViewEncapsulation.None,
  styles: [require('./login.scss')],
  template: require('./login.html'),
})
export class Login implements OnInit {

  public form: FormGroup;
  public username: AbstractControl;
  public password: AbstractControl;
  public submitted: boolean = false;
  public user: User;
  private errorMessage: string;

  constructor(
    fb: FormBuilder,
    private userService: UserService,
    private router: Router
  ) {
    this.form = fb.group({
      'username': ['', Validators.compose([Validators.required, Validators.minLength(4)])],
      'password': ['', Validators.compose([Validators.required, Validators.minLength(4)])]
    });

    this.username = this.form.controls['username'];
    this.password = this.form.controls['password'];
  }

  ngOnInit() {
    let user = localStorage.getItem('accessToken');
    if (user) {
      console.log(' user name' + user);
      this.router.navigateByUrl('pages');
    }
  }

  public onSubmit(values: Object): void {

    this.submitted = true;
    if (this.form.valid) {
      console.log(' login start');
      this.userService.login(this.username.value, this.password.value)
        .then(user => this.login(user), error => console.error(error))
        .catch(() => console.log('error'));
    }
  }

  login(data: User) {
    this.user = data;
    //判断登录结果
    if (this.user && this.user.user_id > 0) {
      console.log(this.user.login_username);
      console.log(this.user.carrier_id);
      localStorage.setItem('accessToken', this.user.login_username);
      localStorage.setItem('loginUsercarrierID', this.user.carrier_id.toString());
      localStorage.setItem('roleId', this.user.role_id.toString());
      this.router.navigate(['/pages']);
    } else {
      this.errorMessage = '用户名或密码错误！';
      console.log('login failed!');
      localStorage.removeItem('accessToken');
    }
    console.log(' login end');
  }
}
